// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-9g5lqt9ibc64c0d5'
})
const xlsx = require('node-xlsx')
// 云函数入口函数
exports.main = async (event, context) => {
 
  //return res
  try {
    let {userdata} = event
    // let res = await cloud.database().collection('menu').get();
    // let userdata = res.result.data
    // return userdata
    //1,定义excel表格名
    let dataCVS = '校服订购信息.xlsx'
    //2，定义存储数据的
    let alldata = [];
    let row = ['姓名', '手机号','年级','班级','身高', '体重','腰围', '订购规格', '订购数量' , '总金额', '订购时间']; //表属性
    alldata.push(row);
    for (let key in userdata) {
      let arr = [];
      arr.push(userdata[key].name);
      arr.push(userdata[key].tele);
      arr.push(userdata[key].grade);
      arr.push(userdata[key].class);
      arr.push(userdata[key].height);
      arr.push(userdata[key].weight);
      arr.push(userdata[key].waist);
      arr.push(userdata[key].specifications);
      arr.push(userdata[key].number);
      arr.push(userdata[key].total_money);
      arr.push(userdata[key].time);
      alldata.push(arr)
    }
    //3，把数据保存到excel里
    var buffer = await xlsx.build([{
      name: "校服采购信息",
      data: alldata
    }]);
    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: dataCVS,
      fileContent: buffer, //excel二进制文件
    })

  } catch (e) {
    console.error(e)
    return e
  }
}

// const wxContext = cloud.getWXContext()

// return {
//   event,
//   openid: wxContext.OPENID,
//   appid: wxContext.APPID,
//   unionid: wxContext.UNIONID,
// }